<template>
	<jk-dialog
		v-model="showDialog"
		title="人机绑定"
		width="940px"
		:show-content-loading="showLoading"
		append-to-body
		:confirm-btn-loading="confirmBtnLoading"
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<div class="padding-top-10">
			<jk-divider-card ref="box1" title="人员信息" icon="el-icon-s-custom" placement="center">
				<el-row :gutter="40">
					<el-col :span="6" class="flex-start-center">
						<span class="emp-machine-form-label">人员</span>
						<el-tag type="info" class="width-100-percent" size="large">{{ ruleForm.name }}</el-tag>
					</el-col>
					<el-col :span="6" class="flex-start-center">
						<span class="emp-machine-form-label">区域</span>
						<el-tag type="info" class="width-100-percent" size="large">{{ ruleForm.workshopName }}</el-tag>
					</el-col>
					<el-col :span="6" class="flex-start-center">
						<span class="emp-machine-form-label">班组</span>
						<el-tag type="info" class="width-100-percent" size="large">{{ ruleForm.groupName }}</el-tag>
					</el-col>
					<el-col :span="6" class="flex-start-center">
						<span class="emp-machine-form-label">岗位</span>
						<el-tag type="info" class="width-100-percent" size="large">{{ ruleForm.postName }}</el-tag>
					</el-col>
				</el-row>
			</jk-divider-card>
			<div ref="box2" class="legend-container">
				<div class="legend-item">
					<div class="legend-item-icon disabled-legend-icon"></div>
					<span>已选</span>
				</div>
				<div class="legend-item">
					<div class="legend-item-icon"></div>
					<span>未选</span>
				</div>
			</div>
			<el-row :gutter="20">
				<el-col :span="16">
					<div ref="box3" class="operation-box-header">
						<span>机台容器：</span>
						<div class="flex-end-center">
							<jk-search-input v-model="ruleForm.workshopName" disabled placeholder="区域" class="search-bar-item-size1 item-gap" size="mini"></jk-search-input>
							<el-select v-model="searchParams.processId" placeholder="工序" clearable size="mini" class="search-bar-item-size1 item-gap">
								<el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
							<jk-search-input v-model="searchParams.nameOrCode" :show-search="true" placeholder="设备编号或名称" class="search-bar-item-size3" size="mini" @on-enter="onSearchBtn"></jk-search-input>
						</div>
					</div>
					<div v-loading="tableLoading" class="machine-container" :style="{height: `${dialogTableHeight - 40}px`}">
						<div class="width-100-percent" :style="{height: `${dialogTableHeight - 84}px`, overflow: 'auto', display: 'inline-block'}">
							<div
								v-for="(item) in machineList"
								:key="item.machineId"
								:style="{cursor: item.isExist ? '' : 'pointer'}"
								:class="item.isExist ? 'forbid machine-container-item' : 'machine-container-item'"
								@click="onChecked(item)"
							>
								<el-tag
									size="mini"
									effect="dark"
									:type="item.isExist ? 'success' : 'primary'"
									class="width-100-percent flex-center"
								>{{ item.machineName }}</el-tag>
							</div>
						</div>
						<div ref="box4" class="flex-center width-100-percent">
							<jk-page
								location="dialog"
								:page-index="searchParams.pageNo"
								:page-sizes="searchParams.pageSizes"
								:page-size="searchParams.pageSize"
								:total="searchParams.count"
								@on-change="onPageChange"
							/>
						</div>
					</div>
				</el-col>
				<el-col :span="8">
					<div class="operation-box-header">
						<span>责任机台：{{ tableData.length }}台</span>
						<el-button size="mini" type="danger" icon="el-icon-delete" plain @click="onClearBtn">清空</el-button>
					</div>
					<div class="emp-machine-container" :style="{height: `${dialogTableHeight - 41}px`}">
						<div
							v-for="(item, index) in tableData"
							:key="item.machineId"
							class="emp-machine-item"
						>
							<el-tag
								size="mini"
								effect="dark"
								type="success"
								class="flex-center"
								closable
								@close="onRemove(index)"
							>{{ item.machineName }}</el-tag>
						</div>
					</div>
				</el-col>
			</el-row>
		</div>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { machinemanagerMachinePage, workforcemanagementEmpMachineUpdate } from '../../../api/machine/machineArchives';
    import { spinProcessPage } from '../../../api/technology/process';
    import vuedraggable from 'vuedraggable';
    import { pageConfig } from '../../../utils/jk/jk-tool';
    export default {
        components: { vuedraggable },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            empItem: {
                type: Object,
                default() {
                    return {};
                }
            }
        },
        mixins: [calHeight],
        data() {
            return {
                tableLoading: false,
                machineList: [],
                processList: [],
                searchParams: {
                    workshopId: null,
                    auditState: 1,
                    nameOrCode: '',
                    processId: null,
                    pageSize: pageConfig.pageSize
                },
                tableData: [],
                scheduleList: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                ruleForm: {}
            };
        },
        methods: {
            onChecked(item) {
                if (!item.isExist) {
                    this.tableData.push(item);
                }
                this.setDisabledMove();
            },
            onPageChange(index) {
                this.$set(this.searchParams, 'pageNo', index);
                this.getMachineListRequest();
            },
            onClearBtn() {
                this.tableData = [];
                this.setDisabledMove();
            },
            onMachineContainerMoveEnd() {
                this.setDisabledMove();
            },
            setDisabledMove() {
                this.machineList = this.machineList.map(x => {
                    return {
                        isExist: !!this.tableData.find(k => k.machineId === x.machineId), // 是否存在，存在的不可拖拽
                        machineId: x.machineId,
                        machineName: x.machineName,
                        machineCode: x.machineCode
                    };
                });
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getMachineListRequest();
            },
            getProcessListRequest() {
                return spinProcessPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.processList = res.data.res;
                    }
                });
            },
            getMachineListRequest() {
                this.tableLoading = true;
                this.machineList = [];
                return machinemanagerMachinePage(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.$set(this.searchParams, 'count', res.data.count);
                        if (res.data.res) {
                            let arr = [];
                            arr = res.data.res ? res.data.res.map(x => {
                                return {
                                    machineId: x.id,
                                    machineName: x.name,
                                    machineCode: x.code
                                };
                            }) : [];
                            // this.machineList = arr.filter(x => !this.tableData.map(k => k.machineId).includes(x.machineId));
                            this.machineList = arr;
                            this.setDisabledMove();
                        } else {
                            this.machineList = [];
                        }
                    }
                });
            },
            onRemove(index) {
                this.tableData.splice(index, 1);
                this.setDisabledMove();
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                return params;
            },
            onConfirmBtn() {
                this.confirmBtnLoading = true;
                workforcemanagementEmpMachineUpdate({
                    id: this.ruleForm.id,
                    empMachineList: this.tableData
                }).then(res => {
                    this.confirmBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$emit('on-finish');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                }
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getProcessListRequest();
                await this.getMachineListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    const cpData = JSON.parse(JSON.stringify(this.empItem));
                    this.ruleForm = cpData;
                    this.$set(this.searchParams, 'workshopId', cpData.workshopId);
                    this.tableData = cpData.empMachineList || [];
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.operation-box-header {
    font-size: 13px;
    margin-bottom: 4px;
    height: 28px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
}
.emp-machine-form-label {
    white-space: nowrap;
    font-size: 13px;
    margin-right: 4px;
}
.emp-machine-container {
    width: 100%;
    box-sizing: border-box;
    border: dashed 1px #19be6b;
    border-radius: 4px;
    padding: 2px;
    overflow: auto;
    .emp-machine-item {
        padding: 2px;
        width: 50%;
        display: inline-block;
        //cursor: move;
    }
}
.machine-container {
    width: 100%;
    border: solid 1px #dcdee2;
    border-radius: 4px;
    padding: 2px;
    box-sizing: border-box;
    .machine-container-item {
        padding: 2px;
        width: calc(100% / 6);
        box-sizing: border-box;
        display: inline-block;
    }
}
.legend-container {
    padding: 16px 0;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    .legend-item {
        display: flex;
        align-items: center;
        margin-right: 20px;
        .legend-item-icon {
            width: 20px;
            height: 10px;
            background: #2b85e4;
            margin-right: 2px;
        }
        .disabled-legend-icon {
            background: #19be6b
        }
    }
}
</style>
